package tp.tecnicasdisenio.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

public class DataBaseUtil {
	
	public static void executeScript(){
		File script= new File("src/test/resources/gestionemails_mysqldump.sql");
		DataBaseUtil.executeScript(LectorPropiedades.getInstance().getPropiedad(LectorPropiedades.NOMBRE_BD), 
				LectorPropiedades.getInstance().getPropiedad(LectorPropiedades.USER_BD), 
				LectorPropiedades.getInstance().getPropiedad(LectorPropiedades.PASSWORD_BD), 
				script.getAbsolutePath(), true);
	}
	
	public static String executeScript (String dbname, String dbuser,
			String dbpassword, String scriptpath, boolean verbose) {
		String output = null;
		try {
			String[] cmd = new String[]{"mysql",
					dbname,
					"--user=" + dbuser,
					"--password=" + dbpassword,
					"-e",
					"\"\\. " + scriptpath + "\""

			};
			System.err.println(cmd[0] + " " + cmd[1] + " " +
					cmd[2] + " " + cmd[3] + " " +
					cmd[4] + " " + cmd[5]);
			Process proc = Runtime.getRuntime().exec(cmd);
			if (verbose) {
				InputStream inputstream = proc.getInputStream();
				InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
				BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

				// read the output
				String line;
				while ((line = bufferedreader.readLine()) != null) {
					System.out.println(line);
				}

				// check for failure
				try {
					if (proc.waitFor() != 0) {
						System.err.println("exit value = " +
								proc.exitValue());
					}
				}
				catch (InterruptedException e) {
					System.err.println(e);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return output;
	}

}
